var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var cors = require("cors");

// 读取router文件夹下的所有文件和文件夹并输出文件名和路由，如果是文件夹，递归调用
const fs = require("fs");
let pathName = path.join(__dirname, "routes");
let routersArr = [];
// 遍历pathName下的所有文件和文件夹,并输出文件名和路由,如果是文件夹,递归调用
/**
 * 读取目录下的所有文件和文件夹
 * @param {*} pathName 目录路径
 * @param {*} routersArr 初始的路由数组
 * @param {*} parentPath 父级路由
 */
function readDirSync(pathName, routersArr = [], parentPath = "/") {
  let pa = fs.readdirSync(pathName);
  pa.forEach(function (ele) {
    // 判断是不是文件夹
    let info = fs.statSync(pathName + "/" + ele);
    if (info.isDirectory()) {
      let obj = {
        path: parentPath + ele,
        name: ele,
        children: [],
      };
      routersArr.push(obj);
      readDirSync(pathName + "/" + ele, obj.children, parentPath + ele + "/");
    } else {
      console.log("file: " + ele);
      // 读取文件内容
      let obj = {
        path:
          parentPath + (ele.split(".")[0] === "index" ? "" : ele.split(".")[0]),
        name: ele.split(".")[0],
        filePath: parentPath + ele,
      };
      routersArr.push(obj);
    }
  });
}
readDirSync(pathName, routersArr);
var app = express();
app.use(cors());

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));

const loadPath = (routers = routersArr) => {
  routers.forEach((item) => {
    if (!item.children) {
      let router = require(path.join(
        __dirname,
        "./routes/",
        item.filePath.split(".")[0]
      ));
      app.use(item.path, router);
    } else {
      loadPath(item.children);
    }
  });
};
// 动态加载路由
loadPath();

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;
